﻿namespace Yaaf.WP7.NativeAccess.IO.Internals.HTC.COM_NativeAccess
{
    using Microsoft.Phone.InteropServices;

    using System;
    using System.Collections.Generic;
    using System.IO;

    using Yaaf.WP7.NativeAccess.ComWrapper.HTC.COM_NativeAccess;

    internal class Directory
    {
        public static string[] GetDirectories(string path, string searchString)
        {
            FileSystemEntryStructure fileSystemEntryStructure;
            List<string> list = new List<string>();
            IntPtr zero;
            if ((FileSystem.StartEnumerateDirectory(Path.Combine(path, searchString), out fileSystemEntryStructure, out zero) == 0) || (zero == new IntPtr(-1)))
            {
                var error = Marshal.GetLastWin32Error();
                throw new IOException("Error: " + error);
            }
            if ((fileSystemEntryStructure.attributes & FileAttributes.Directory) == FileAttributes.Directory)
            {
                list.Add(fileSystemEntryStructure.path);
            }
            while (true)
            {
                do
                {
                    if (FileSystem.NextElement(zero, out fileSystemEntryStructure) == 0)
                    {
                        goto Label_0085;
                    }
                }
                while ((fileSystemEntryStructure.attributes & FileAttributes.Directory) != FileAttributes.Directory);
                list.Add(fileSystemEntryStructure.path);
            }
        Label_0085:
            FileSystem.CloseEnumerator(zero);
            return list.ToArray();
        }

        public static string[] GetFiles(string path, string searchString)
        {
            FileSystemEntryStructure fileSystemEntryStructure;
            List<string> list = new List<string>();
            IntPtr zero = IntPtr.Zero;
            if ((FileSystem.StartEnumerateDirectory(Path.Combine(path, searchString), out fileSystemEntryStructure, out zero) == 0) || (zero == new IntPtr(-1)))
            {
                return list.ToArray();
            }
            if ((fileSystemEntryStructure.attributes & FileAttributes.Directory) != FileAttributes.Directory)
            {
                list.Add(fileSystemEntryStructure.path);
            }
            while (true)
            {
                do
                {
                    if (FileSystem.NextElement(zero, out fileSystemEntryStructure) == 0)
                    {
                        goto Label_007F;
                    }
                }
                while ((fileSystemEntryStructure.attributes & FileAttributes.Directory) == FileAttributes.Directory);
                list.Add(fileSystemEntryStructure.path);
            }
        Label_007F:
            FileSystem.CloseEnumerator(zero);
            return list.ToArray();
        }
    }
}

